<?php
// 主题处理器
// 从触屏版网页进行分析

namespace App\Handlers;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\DomCrawler\Crawler;
use Carbon\Carbon;
use Cache;

class SubjectHandler
{
	protected $crawler;

	public function __construct($filename)
	{
		$this->crawler = new Crawler($this->getContent($filename));
	}

	private function getContent($filename) 
	{
		return $html = Storage::disk('tieba')->get($filename);
	}

	private function deleteFile($filename)
	{
		return $html = Storage::disk('tieba')->delete($filename);
	}
	// 回复数
	public function reply_count ()
	{
		return $this->crawler->filter('li.l_reply_num span.red')->text();
	}
	// 吧名称
	public function name()
	{
		$name = $this->crawler->filter('div#i_head a.post_title_text')->text();
		return str_replace('吧', '', trim($name));
	}
	// 标题
	public function title()
	{
		return $this->crawler->filter('h3.core_title_txt.pull-left.text-overflow')->attr('title');
	}
	// 主题内容
	public function content()
	{
		return $this->crawler->filter('div.d_post_content_firstfloor cc div.d_post_content')->html();
	}
	// 楼层信息

	public function floor()
	{
		$arr = $this->crawler
			->filter('ul#pblist li[tid]')
			->each(function (Crawler $node, $i) {
    			//return $node->html();
    			
    			$content = trim($node->filter('div.content')->html());
    			$c = new Crawler($content);
    			$voice = [];
    			if($c->filter('div.voice_music')->count())
    			{
    				$voice = [
    					'url' => $c->filter('div.voice_music')->attr('data-url'),
    					'time' => $c->filter('div.voice_music')->attr('data-time'),
    				];
    			}
    			
    			return [
    				'content' => $content,
    				'info' => $this->trueName($node->attr('data-info')),
    				'author' => [
    					'name' => trim($node->filter('a.user_name')->text()),
    					'level' => trim($node->filter('span.level')->text()),
    				],
    				'floor' => $node->attr('fn'),
    				'time' => trim($node->filter('span.list_item_time')->text()),
    				'reply_count' => $node->filter('div.j_floor_panel')->attr('data-list-count'),
    				'pid' => $node->attr('tid'),
    				'voice' => $voice,
    			];
			});
		return $arr;
	}
	public function floorContent()
	{

	}

	public function trueName($info)
	{
		return json_decode($info, TRUE);
	}
}